<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>硬件平台</el-breadcrumb-item>
      <el-breadcrumb-item>硬件管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-row :gutter="24">
        <el-col :offset="5" :span="10">
          <!-- 搜索添加 -->
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" clearable @clear="getHardwareList">
            <el-button slot="append" icon="el-icon-search" @click="getHardwareList"></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加硬件</el-button>
        </el-col>
      </el-row>
      <!-- 硬件列表 -->
      <el-table :data="hardwarelist" border highlight-current-row :row-class-name="tableRowClassName"
                :default-sort="{prop: 'name', order: 'descending'}">
        <el-table-column type="index" fixed></el-table-column>
        <el-table-column label="名称" fixed prop="name" sortable></el-table-column>
        <el-table-column label="mac" fixed prop="mac"></el-table-column>
        <el-table-column label="ip" prop="ip"></el-table-column>
        <el-table-column label="序列号" prop="serialNumber"></el-table-column>
        <el-table-column label="生产日期" prop="dateProduction" sortable :formatter="formatTime"></el-table-column>
        <el-table-column label="类型" prop="type"></el-table-column>
        <el-table-column label="生产者" prop="producers"></el-table-column>
        <el-table-column label="官网" prop="website"></el-table-column>
        <el-table-column label="位置" prop="position"></el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(scope.row.id)"></el-button>
            <!--            &lt;!&ndash; 详情 &ndash;&gt;-->
            <!--            <el-tooltip effect="dark" content="详情" placement="top-start" :enterable="false">-->
            <!--              <el-button type="info" icon="el-icon-setting" size="mini"></el-button>-->
            <!--            </el-tooltip>-->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="queryInfo.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog title="添加硬件" :visible.sync="addDialogVisible"
               @close="getHardwareList">
      <new-hardware v-on:closeAddDialog="addDialogVisible = false"></new-hardware>
    </el-dialog>
    <!-- 修改硬件对话框 -->
    <el-dialog title="修改硬件信息" :visible.sync="editDialogVisible"
               @colse="getHardwareList">
      <edit-hardware v-on:closeEditDialog="closeEditDialog"
                     :edit-form="editform"></edit-hardware>
    </el-dialog>
  </div>
</template>
<style>
.el-table .warning-row {
  background: #fae9ca;
}

.el-table .success-row {
  background: #f0f9eb;
}

.el-table .danger-row {
  background: #fccfcf;
}
</style>
<script>
import NewHardware from "@/components/hardware/newHardware";
import editHardware from "@/components/hardware/editHardware";

export default {
  components: {NewHardware, editHardware},
  data() {
    return {
      // 请求数据
      queryInfo: {
        query: "",
        pageNum: 1,
        pageSize: 5
      },
      file: null,
      editform: {
        hardware: null,
        images: null,
        ids: null
      },
      hardwarelist: [],// 硬件列表
      total: 0, // 最大数据记录
      addDialogVisible: false,// 对话框显示
      // 控制修改用户对话框显示/隐藏
      editDialogVisible: false,
    };
  },
  created() {
    this.getHardwareList();
  },
  methods: {
    async getHardwareList() {
      // 调用post请求
      const {data: res} = await this.$http.get("getHardwareList", {
        params: this.queryInfo
      });
      this.hardwarelist = res.data; // 将返回数据赋值
      this.total = res.numbers; // 总个数
    },
    // 监听pageSize改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getHardwareList(); // 数据发生改变重新申请数据
    },
    // 监听pageNum改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getHardwareList(); // 数据发生改变重新申请数据
    },
    tableRowClassName({row, rowIndex}) {
      if (row.status === 1) {
        return 'warning-row';
      } else if (row.status === 0) {
        return 'success-row';
      } else if (row.status === -1) {
        return 'danger-row';
        return '';
      }
    },
    formatTime: function (row, column) {
      if(row.dateProduction !==''){
        return row.dateProduction.substring(0, 10)
      }
    },
    // 展示修改框
    async showEditDialog(id) {
      const {data: res} = await this.$http.get("getUpdateHardware?id=" + id);
      res.hardware.position = res.hardware.position.split(',')
      let images = res.images
      let fileList = []
      if (images.length !== 0) {
        for (let i = 0; i < images.length; i++) {
          let image = this.dataURLtoBlob(images[i])
          let file = URL.createObjectURL(image)
          fileList.push({id: res.ids[i], url: file});
        }
      }
      res.images = fileList
      this.editform = res;
      this.editDialogVisible = true;
      // this.$router.push("test");
    },
    handlesrcschange(file, filelist) {
      console.log(filelist)
    },
    // 删除按钮
    async deleteUser(id) {
      // 弹框
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 成功删除为confirm 取消为 cancel
      if (confirmResult != 'confirm') {
        return this.$message.info("已取消删除");
      }
      const {data: res} = await this.$http.delete("deleteHardware?id=" + id);
      if (res != "success") {
        return this.$message.error("操作失败！！！");
      }
      this.$message.success("操作成功！！！");
      this.getHardwareList();
    },
    //将base64转换为blob
    dataURLtoBlob(dataurl) {
      let bstr = atob(dataurl),
          n = bstr.length,
          u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new Blob([u8arr], {
        type: "image/jpeg"
      });
    }
    ,
    closeEditDialog(){
      this.editDialogVisible = false;
      this.getHardwareList();
    }
  }
}
;
</script>
